﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GPRSLib;
using System.IO.Ports;
using System.Threading;
namespace GPRSForm
{
    public partial class Form1 : Form
    {
        SerialPort port = null;
        gmsClass gms = null;
        DataTable datatable = null;
        DataTable dataSend = null;
        Database.DataBase database = null;
        Thread autoSendThread = null;
       
        public Form1()
        {
            InitializeComponent();
            initComponent();
            initDataTable();
            
        }
        public void initDataTable()
        {
            dataGridView_SMS.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            
            datatable = new DataTable("SMS");
            datatable.Columns.Add("STT");
            datatable.Columns.Add("SDT");
            datatable.Columns.Add("Content");
        }
        public void initComponent()
        {
            tabSMS.TabPages.Remove(tabReceive);
            tabSMS.TabPages.Remove(tabSend);
            #region add port item
            portCbx.Items.Add("COM1");
            portCbx.Items.Add("COM2");
            portCbx.Items.Add("COM3");
            portCbx.Items.Add("COM4");
            portCbx.Items.Add("COM5");
            portCbx.Items.Add("COM6");
            portCbx.SelectedIndex = 4;
            #endregion
            #region add baudrate
            baudRateCbx.Items.Add(4800);
            baudRateCbx.Items.Add(9600);
            baudRateCbx.Items.Add(115200);
            baudRateCbx.SelectedIndex = 2;
            #endregion

        }

        private void ConnectBt_Click(object sender, EventArgs e)
        {
            int baudRate ;
            string portName = null;
            try
            {
                portName = (string)portCbx.SelectedItem;
                baudRate =  (int)baudRateCbx.SelectedItem;
                gms = new gmsClass();
                database = new Database.DataBase();
                port = gms.OpenPort(portName, baudRate, 8, 300, 300);
                this.tabSMS.TabPages.Add(tabSend);
                this.tabSMS.TabPages.Add(tabReceive);
                this.tabSMS.TabPages.Remove(tabMain);
                this.autoSendThread = new Thread(new ThreadStart(autoSend));
                this.autoSendThread.IsBackground = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        

        /*
        * method send SMS
        */
        public bool sendSMS(string phoneNumber, string smg)
        {
            
            // send message with phone and message
            if (gms.sendMsg(port, phoneNumber, smg))
            {
                //this.resultLabel.Text = "Message is sent successfully";
                return true;
            }
            else
            {
                //this.resultLabel.Text = "Fail to sent message";
                return false;
            }
        }
        /*
         * method readSMS 
         */


        public DataTable readSMS()
        {
            
            string readOption = null;
            if (radioReadUn.Checked == false && radioReadAll.Checked == true)
            {
                readOption = "AT+CMGL=\"ALL\"";
            }
            else
            {
                readOption = "AT+CMGL=\"REC UNREAD\"";
            }

            List<ShortMessage> messages = gms.ReadSMS(port, readOption);
            foreach (ShortMessage message in messages)
            {
                datatable.Rows.Add(message.Index, message.Sender, message.Message);
            }
            return datatable;
        }

        private void send_Click(object sender, EventArgs e)
        {
            string phoneNum = null;
            string text = null;
            try
            {
                phoneNum = this.phoneText.Text;
                text = this.smsText.Text;
                sendSMS(phoneNum,text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public delegate void logDelegate(string phone, string text);
     
        public void logMessage(string phone, string text)
        {
            if (InvokeRequired)
            {
                this.Invoke(new logDelegate(logMessage), phone,text);
            }
            else
            {
                phoneText.Text = phone;
                smsText.Text = text;
            }
           
        }
        private void autoSend()
        {
            bool result = false;
            double date;
            string phone = "";
            string text = "";
            string id;
            while (true)
            {
                Thread.Sleep(1000);
                dataSend = database.getSMS();
                for (int i = 0; i < dataSend.Rows.Count; i++)
                {
                    
                    id = dataSend.Rows[i]["sms_id"].ToString();
                    phone = dataSend.Rows[i]["telephone_no"].ToString();
                    text = dataSend.Rows[i]["content"].ToString();
                    date = GPRSForm.SMS.CommonFunction.ConvertToUnixTimestamp(DateTime.Now);
                    result = sendSMS(phone, text);
                    logMessage(phone, text);
                    if (result)
                    {
                        database.updateSMS(id,date);
                        result = false;
                    }
                    Thread.Sleep(1000);
                }
            }
        }
        private void radio_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton radioCurrent = sender as RadioButton;
           
        }

        private void receiveBt_Click(object sender, EventArgs e)
        {
            DataTable datatable = null;
            try
            {
                datatable =  readSMS();
                if (datatable != null)
                {
                    dataGridView_SMS.DataSource = datatable;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btAutoSend_Click(object sender, EventArgs e)
        {
            this.btSend.Enabled = false;
            this.btAutoSend.Enabled = false;
            this.btStopAutosend.Enabled = true;
            this.phoneText.Enabled = false;
            this.smsText.Enabled = false;
            if (this.autoSendThread.IsAlive)
                this.autoSendThread.Start();
            else
            {
                this.autoSendThread = new Thread(new ThreadStart(autoSend));
                this.autoSendThread.Start();
            }
        }

        private void btStopAutosend_Click(object sender, EventArgs e)
        {
            this.btSend.Enabled = true;
            this.btAutoSend.Enabled = true;
            this.btStopAutosend.Enabled = false;
            this.phoneText.Enabled = true;
            this.smsText.Enabled = true;
            this.autoSendThread.Abort();
        }
    }
}
